import fileClient from "@/data-services/file-http";
import { T_Camera_Video_Row, T_RectGraphResultItem, T_Warn_List_Row } from "@/pages/components/types";
import { extractFileName } from './index'
import { i18n } from '@/vue-i18n'
import { GetEquipments_CameraList } from "@/data-services/api";
import axios from "axios";
import appEnvironment from '@/app-environments'
const $t = i18n.global.t
const {
    networkHosts: {
        apiServer1: {
            fullHost,
        },
    },
} = appEnvironment

// 视频下载
export async function videoDownload(row: any, selCameraVideoVal: T_Camera_Video_Row[]) {
    let params = []
    if (row) {
        // 单个下载
        params[0] = row.storage_addr ? `${row.video_url}&storage_addr=${row.storage_addr}` : row.video_url ?? ''
    } else {
        const videoUrl = selCameraVideoVal.map(item => {
            return item.storage_addr ? `${item.video_url}&storage_addr=${item.storage_addr}` : item.video_url ?? ''
        })
        params = videoUrl.filter(item => item)
    }

    params.forEach(async (item, i) => {
        try {
            const url = `/data/collection/v2/download?video=${item}`
            const res = await fileClient.get(url)
            const filename = item.split('/').pop() || ''
            const name = extractFileName(filename)
            if (res.data) {
                const link = document.createElement('a')
                const blob = new Blob([res.data], { type: 'video/mp4' })
                link.href = URL.createObjectURL(blob)
                link.download = name || `video_${i}` // 设置下载文件名
                link.click()
            }
        } catch (error: any) {
            ElMessage({
                type: 'error',
                message: error?.message || $t('下载失败'),
            })
        }
    })
}


// 视频播放
export async function videoPlay(
    row: T_Warn_List_Row
): Promise<{
    videourl: string
    cameraIp: string
    startTime: number
    results: T_RectGraphResultItem[]
}> {
    const params = { /*...*/ }
    const res = await GetEquipments_CameraList(params)

    if (res.code !== 0 || !res.data?.devicesList) {
        throw new Error('获取设备列表失败')
    }

    let videourl = row.video ? `${fullHost}${row.video}` : ''
    if (row.storage_addr) {
        videourl += `?storage_addr=${row.storage_addr}`
    }

    const { data } = await axios.get(videourl)

    return {
        videourl,
        cameraIp: row.addr,
        startTime: row.video_start || 0,
        results: data || []
    }
}



